package cn.ac.sec.oil.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import cn.ac.sec.oil.data_analysis.protocol.FileOperate;

/**
 * 功能：测试server的client
 * 在运行时需要传入参数,格式:host port
 */
public class NettyClient {
	
	public static void main(String[] args) throws Exception {
		
		String host = args[0]; //在程序运行时传入参数
		int port = Integer.parseInt(args[1]);
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		FileOperate fileOperate = new FileOperate();
		String packetStr; //保存一个数据包

		try {
			
			Bootstrap b = new Bootstrap(); // (1)
			b.group(workerGroup); // (2)
			b.channel(NioSocketChannel.class); // (3)
			b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
			b.handler(new NettyClientInitializer()); //初始化
			Channel ch = b.connect(host, port).sync().channel();
			
			for (int k = 0; k < 3; k++) { //发送n次测量数据
				
				for (int i = 1; i < 7; i++) { //发送6个数据包
					packetStr = fileOperate.FileToStr("E://data/data2/packet" + i + ".txt", "gbk");
					System.out.println("packet" + i + ": " + packetStr);
					Thread.sleep(2000);
					
					ch.writeAndFlush(packetStr + "\r\n"); //将line内容进行发送
				}
			}
			
			while(true) { //继续阻塞，防止服务器报错
				
			}

		} finally {
			workerGroup.shutdownGracefully();
		}
	}
}
